package com.bobi.tfca.ui.mainnavigation.message.groupcreation

import android.annotation.SuppressLint
import android.os.Bundle
import android.widget.Toast
import androidx.navigation.findNavController
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bobi.tfca.R
import com.bobi.tfca.base.BaseFragment
import com.bobi.tfca.databinding.FragmentCreateGroupBinding
import com.bobi.tfca.network.response.MemberResponse
import com.bobi.tfca.ui.adapter.GroupMemAddAdapter

class GroupCreationFragment : BaseFragment<FragmentCreateGroupBinding, GroupCreationFragmentVM>(
    FragmentCreateGroupBinding::inflate,
    GroupCreationFragmentVM::class.java,
    true
) {
    // 添加的成员RV
    private lateinit var memberRV : RecyclerView

    @SuppressLint("ResourceType", "UseRequireInsteadOfGet")
    override fun initFragment(
        binding: FragmentCreateGroupBinding,
        viewModel: GroupCreationFragmentVM?,
        savedInstanceState: Bundle?
    ) {
        // 设置头部菜单的按钮
        setTopPanelStyle(viewModel!!, binding)

        // 初始化RecyclerView
        initRecyclerView(viewModel, binding)

        // 添加按钮
        binding.addButton.setOnClickListener {
            val inputText = binding.searchBox.text.toString()
            val memberId = inputText.toIntOrNull()
            if (memberId != null) {
                viewModel.getMemberById(publicViewModel!!, memberId, this)
            } else {
                Toast.makeText(requireContext(), "请输入有效ID", Toast.LENGTH_SHORT).show()
            }
        }

        // 设置监听
        viewModel.members.observe(viewLifecycleOwner){
            val adapter : GroupMemAddAdapter = memberRV.adapter as GroupMemAddAdapter
            adapter.memberResponseList = it
            adapter.notifyDataSetChanged()
        }
    }

    /**
     * 设置顶部面板的样式
     */
    private fun setTopPanelStyle(
        viewModel: GroupCreationFragmentVM,
        binding: FragmentCreateGroupBinding
    ) {
        val topPanel = binding.topPanel
        val leftImage = topPanel.leftImage
        leftImage.setOnClickListener{
            requireActivity().findNavController(R.id.app_nav).navigateUp()
        }

        val rightButton = topPanel.rightButton
        rightButton.text = "确认"
        rightButton.setOnClickListener {
            val adapter = memberRV.adapter as GroupMemAddAdapter
            val choseMemberList = adapter.memberResponseList
            val choseMemberIdList: List<Int> = choseMemberList.map { it.memberId }
            val groupName = binding.setGroupName.text.toString()
            viewModel.createGroup(publicViewModel!!,groupName, choseMemberIdList, this)
        }

        val title = topPanel.titleText
        //  动态群聊名称
        title.text = "建群"
    }

    /**
     * 初始化RV
     */
    private fun initRecyclerView(
        viewModel: GroupCreationFragmentVM?,
        binding: FragmentCreateGroupBinding
    ) {
        // 初始化RV
        memberRV = binding.memberRV

        // 设置布局排列方式，默认垂直排列
        val linearLayoutManager = LinearLayoutManager(binding.root.context)
        linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
        memberRV.layoutManager = linearLayoutManager
        // 添加分隔线
        memberRV.addItemDecoration(
            DividerItemDecoration(
                binding.root.context,
                LinearLayoutManager.VERTICAL
            )
        )
        // 绑定adapter
        val memberAdapter = GroupMemAddAdapter(this, arrayListOf())
        memberAdapter.setOnItemClickListener(object : GroupMemAddAdapter.OnItemClickListener {
            override fun onItemClick(position: Int) {
                // 点击按钮后取消添加
                val list : ArrayList<MemberResponse> = viewModel!!.members.value ?: ArrayList()
                if (list.isNotEmpty()) {
                    list.removeAt(position)
                    viewModel.members.value = list
                }
            }
        })
        memberRV.adapter = memberAdapter
    }
}